<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    :title="getTitle"
    width="35%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup name="DictDetailModal">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './config-option';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { saveConfigApi, updateConfigApi } from '/@/api/sys/config';
  import { initConfigCache } from '/@/utils/cache/configCache';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const getTitle = computed(() => (!unref(isUpdate) ? '新增系统配置' : '编辑系统配置'));

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
  });

  const configId = ref();
  const groupId = ref();
  const isUpdate = ref(true);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    groupId.value = data.groupId;
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      configId.value = data.record.configId;
      setFieldsValue({
        ...data.record,
      });
    }
    setModalProps({ confirmLoading: false });
  });

  const emit = defineEmits(['success']);

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      let res;
      if (unref(isUpdate)) {
        const param = { ...values, configId: configId.value, groupId: groupId.value };
        res = await updateConfigApi(param);
      } else {
        const param = { ...values, groupId: groupId.value };
        res = await saveConfigApi(param);
      }
      initConfigCache();
      createMessage.success(res.msg);
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
